package controllers

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"yikexing.com.cn/wyws/models"
	_ "yikexing.com.cn/wyws/services/sqlstore"
)

// 基本请求接口
type BaseController struct {
	beego.Controller
}

func (b *BaseController) checkCommand(m models.BaseModel) error {
	valid := validation.Validation{}
	isValid, err := valid.Valid(m)
	if err != nil {
		beego.Debug(fmt.Sprintf("执行请求参数校验失败:%s", err))
		return errors.New(fmt.Sprintf("执行请求参数校验失败:%s", err))
	}
	if !isValid {
		message := ""
		for _, err := range valid.Errors {
			message = fmt.Sprintf("%s [%s]:%s;", message, err.Key, err.Message)
		}
		beego.Debug(message)
		//b.returnFormatJsonData(1001, nil, message)
		return errors.New(message)
	}
	return nil
}

func (b *BaseController) returnFormatJsonData(status int, data interface{}, message string) {
	b.Data["json"] = models.ReturnInfo{
		Status:  status,
		Data:    data,
		Message: message,
	}
}

// 提供命令解析和命令验证一体式方法
func (b *BaseController) parseAndValidateCommand(cmdObject interface{}) error {
	err := json.Unmarshal(b.Ctx.Input.RequestBody, cmdObject)
	beego.Debug(fmt.Sprintf("cmd in parseAndValidateCommand and the value is : %s", cmdObject))
	if err != nil {
		return fmt.Errorf("Command对象格式转换成Json不成功, %s", err)
	}
	//完成校验
	if err = b.checkCommand(cmdObject); err != nil {
		return err
	}
	return nil
}
